/**
 * @fileoverview This is a file where deprecation checks are disabled.
 * @suppress {undefinedVars}
 */
// the above is for the Google Closure Compiler ant task

//if (window.addEventListener) {
//	  window.addEventListener("storage", handle_storage, false);
//	} else {
//	  window.attachEvent("onstorage", handle_storage);
//	};
	
//	alert("Tore : " + document.getElementById('main_board').rows[1].cells[1]);

//var gameShootInfoWhatIsGoingToReplayed='currentGameShootInfo';


var oldGameIndex = 0;

function testing(){
	var cellinfo= document.getElementById('main_board').rows[1].cells[1];
	//cellinfo= document.getElementById('side_board').rows[1].cells[1];
    var y = cellinfo.cellIndex;
    var x = cellinfo.parentNode.rowIndex;
    console.log("Cell: "+ y + " Row: " + x );
    markCell(cellinfo, 1);
}
//function testing2(){
//	//var names = [1, 2 ,3, 4 ];
//	//localStorage['names']=JSON.stringify(names);
//	var storedNames=JSON.parse(localStorage['names']);
//	console.log(storedNames);
//	
//}

//function testing3(){
//	
//	cellinfo= document.getElementById('side_board').rows[1].cells[1];
//    var y = cellinfo.cellIndex;
//    var x = cellinfo.parentNode.rowIndex;
//    console.log("Cell: "+ y + " Row: " + x );
//    markSbCell(cellinfo, 1);
//}

var saveShootingsList=[];
function saveShooting(cell, row, type, owner){
	// owner - 0 = you ; 1= opponent
	// type - reperesents cell type 1,2,3
	var shootinfo= [cell, row, type,owner];
	//localStorage['game1']=JSON.stringify(shootinfo);
	saveShootingsList.push(shootinfo);
	console.log(saveShootingsList);
	localStorage['currentGameShootInfo']=JSON.stringify(saveShootingsList);
	
}

function replayGame (){
		cleanTables();
		var i=0;
		var replayableShootingsList = JSON.parse(localStorage['LastGameShootInfo']);
		replayableShootingsList=replayableShootingsList[oldGameIndex];
		var timer= setInterval(function() {
			if (i<replayableShootingsList.length){
			var cell= replayableShootingsList[i][0];
			var row= replayableShootingsList[i][1];
            var coords = [row, cell];
            var shotType = replayableShootingsList[i][2];
			if (replayableShootingsList[i][3] == 0){
                // your shot
                markCell(coords, shotType);
                if (shotType === 1) {
                    // the ship sank, so colour the other cells as well
                    colourShip(coords, [coords]);
                }
			}else{
                // the opponent's shot
                markSbCell(coords, shotType);
                if (shotType === 1) {
                    // the ship sank, so colour the other cells as well
                    colourSbShip(coords, [coords]);
                }
			}
			i++;
			
		}
			else{
				clearInterval(timer);
			}
		}, 1000);
		
	    
	}

function isEmpty(el) {
    return (/^(\s|&nbsp;)*$/.test(el.innerHTML));
}

function contains(element, array) {
    for (var i = 0; i < array.length; i ++) {
        if (element[0] == array[i][0] && element[1] == array[i][1]) {
            return true;
        }
    }
    return false;
}

function colourShip(coords, checked) {
    for (var row = coords[0]-1; row <= coords[0]+1; row++) {
        for (var col = coords[1]-1; col <= coords[1]+1; col++) {
            if (row >= 1 && row <= 10 && col >= 1 && col <= 10) {
                var cs = [row, col];
                console.log("looking at coords: " + cs);
                var cell = document.getElementById("main_board").rows[row].cells[col];
                if (!isEmpty(cell) && !contains(cs, checked) && cell.innerHTML != "<h3>X</h3>" && cell.innerHTML != "<p>X</p>") {
                    console.log("colouring coords: " + cs);
                    checked.push(cs);
                    markCell(cs, 4);
                    colourShip(cs, checked);
                }
            }
        }
    }
}

function colourSbShip(coords, checked) {
    for (var row = coords[0]-1; row <= coords[0]+1; row++) {
        for (var col = coords[1]-1; col <= coords[1]+1; col++) {
            if (row >= 1 && row <= 10 && col >= 1 && col <= 10) {
                var cs = [row, col];
                var cell = document.getElementById("side_board").rows[row].cells[col];
                if (!isEmpty(cell) && !contains(cs, checked) && cell.innerHTML != "<h3>X</h3>" && cell.innerHTML != "<p>X</p>") {
                    checked.push(cs);
                    markSbCell(cs, 4);
                    colourSbShip(cs, checked);
                }
            }
        }
    }
}

function replayGame2 (){
    cleanTables();
    var replayableShootingsList = JSON.parse(localStorage['LastGameShootInfo']);
    replayableShootingsList=replayableShootingsList[oldGameIndex];
    var ii=0;
       $("#previous").click(function(){
           if (ii != 0){
               ii--;
               var cell= replayableShootingsList[ii][0];
               var row= replayableShootingsList[ii][1];
               var coords = [row, cell];
               var shotType = replayableShootingsList[ii][2];
               if (replayableShootingsList[ii][3] == 0){
                   var deleteCellinfo= document.getElementById('main_board').rows[row].cells[cell];
                   if (shotType === 1) {
                       // remove sinking colour from the ship's cells
                       removeColour(coords, []);
                   }
               }else{
                   var deleteCellinfo= document.getElementById('side_board').rows[row].cells[cell];
                   if (shotType === 1) {
                       // remove sinking colour from the ship's cells
                       removeSbColour(coords, []);
                   }
               }
               deleteCellinfo.innerHTML = "";
//               $(deleteCellinfo).removeClass("checked");


//			   	console.log(i);
           }

              });

       $("#next").click(function(){
           if (ii<replayableShootingsList.length){
               var cell= replayableShootingsList[ii][0];
               var row= replayableShootingsList[ii][1];

               var coords = [row, cell];
               var shotType = replayableShootingsList[ii][2];
               if (replayableShootingsList[ii][3] == 0){
                   // your shot
                   markCell(coords, shotType);
                   if (shotType === 1) {
                       // the ship sank, so colour the other cells as well
                       colourShip(coords, [coords]);
                   }
               }else{
                   // the opponent's shot
                   markSbCell(coords, shotType);
                   if (shotType === 1) {
                       // the ship sank, so colour the other cells as well
                       colourSbShip(coords, [coords]);
                   }
               }

        //	   replayManually(ii);
               ii++;
//				   console.log(i);
           }
              });

//		   function replayManually(ii){
//   
//		
//		   }

}

function removeColour(coords, checked) {
    for (var row = coords[0]-1; row <= coords[0]+1; row++) {
        for (var col = coords[1]-1; col <= coords[1]+1; col++) {
            if (row >= 1 && row <= 10 && col >= 1 && col <= 10) {
                var cs = [row, col];
                console.log("looking at coords: " + cs);
                var cell = document.getElementById("main_board").rows[row].cells[col];
                if (!isEmpty(cell) && !contains(cs, checked) && cell.innerHTML != "<h3>X</h3>" && cell.innerHTML != "<p>X</p>") {
                    console.log("colouring coords: " + cs);
                    checked.push(cs);
                    $(cell).removeClass("checked");
                    removeColour(cs, checked);
                }
            }
        }
    }
}

function removeSbColour(coords, checked) {
    for (var row = coords[0]-1; row <= coords[0]+1; row++) {
        for (var col = coords[1]-1; col <= coords[1]+1; col++) {
            if (row >= 1 && row <= 10 && col >= 1 && col <= 10) {
                var cs = [row, col];
                var cell = document.getElementById("side_board").rows[row].cells[col];
                if (!isEmpty(cell) && !contains(cs, checked) && cell.innerHTML != "<h3>X</h3>" && cell.innerHTML != "<p>X</p>") {
                    checked.push(cs);
                    $(cell).removeClass("checked");
                    removeSbColour(cs, checked);
                }
            }
        }
    }
}

function cleanTables(){
	for (var i=1; i<11; i++){
		for (var j=1; j<11; j++){
	var square = document.getElementById("main_board").rows[i].cells[j];
    // remove ships from main board
    square.innerHTML = "";
    var square2 = document.getElementById("side_board").rows[i].cells[j];
    square2.innerHTML = "";
		}
	}
//	replayGame ();
}




////Create an object.
//var myObject = {};
// 
//// Store the object.
//localStorage.setItem( "myObject", myObject );
// 
//// Now, get the value and test the data type.
//console.log(
//"typeof( myObject ) ---",
//typeof( localStorage.getItem( "myObject" ) ));


function savePlayedGames () {
	if (localStorage['LastGameShootInfo'] != null){
		var temp = JSON.parse(localStorage['LastGameShootInfo']);
		temp.push(saveShootingsList);
		localStorage['LastGameShootInfo']=JSON.stringify(temp);
	}else{
		var shootList = [];
		shootList.push(saveShootingsList);
		localStorage['LastGameShootInfo']=JSON.stringify(shootList);
	}
	
}

function getOldGameListLength(){
	var temp = JSON.parse(localStorage['LastGameShootInfo']);
	return temp.length;
	}



function savePlayers() {
    var date = new Date().toLocaleString();
    var username = localStorage.getItem("username");
    var opponent = localStorage.getItem("opponent");
    var game = {"date": date, "username": username, "opponent": opponent};

    if (localStorage['PlayersInfo'] != null){
        var games = JSON.parse(localStorage['PlayersInfo']);
        console.log("replay.js: players: " + games);
        console.log("replay.js: players[0]: " + games[0]);
    }else{
        var games = [];
    }
    games.push(game);
    localStorage['PlayersInfo']=JSON.stringify(games);
}